/*
	Written By Pradipna Nepal
	www.pradsprojects.com

	Copyright (C) 2012 Prads Projects
	Please read COPYING.txt included along with this source code for more detail.
	If not included, see http://www.gnu.org/licenses/
*/

#include "libStructTable.h"

bool StructureTable::createStructTable(const TokenModule *module, StructTable *tOut) {
	unsigned int moduleSize = module->lines.size();
	StructEntry structEntry;

	structEntry.name = string();

	for (unsigned int i = 0; i < moduleSize; ++i) {
		if (module->lines[i].lineType == TL_STRUCT) {
			structEntry.name = module->lines[i].tokens[1].getValue();
			while (++i < moduleSize) {
				if (module->lines[i].lineType == TL_CLOSE_SCOPE) {
					break;
				} else if (module->lines[i].lineType == TL_VAR_DECLARE) {
					for (unsigned int ti = 1; ti < module->lines[i].tokens.size(); ++ti) {
						switch (module->lines[i].tokens[ti].getToken()) {
							case TOKEN_IDENTIFIER:
								structEntry.members.push_back(module->lines[i].tokens[ti].getValue());
								break;
							case TOKEN_SEMICOLON:
								continue;
							default:
								{
									string err;
									err = "In struct " + structEntry.name + "...";
									printError(ERROR_SYNTAX, err.c_str());
									return false;
								}
						}
					}
				} else  {
					string err;
					err = "In struct " + structEntry.name + ", only var can be declared inside a struct...";
					printError(ERROR_SYNTAX, err.c_str());
					return false;
				}
			}
			tOut->insert(StructTable::value_type(fnvHash(structEntry.name.c_str(), structEntry.name.size()), 
						structEntry));
			structEntry.name = string();
			structEntry.members.clear();
		}
	}

	return true;
}